--MAP VOTING
local VoteListView = nil
HasVoted = false
MY_LAST_VOTE = 0
function GM:VoteMap()
	local selectedMap = ""
	--if it exists don't recreate it.
	if ( IsValid(self.VoteMapPanel) ) then return end
	
	self.VoteMapPanel = vgui.Create( "DFrame", self )
	self.VoteMapPanel:SetPos( 50,50 )
	self.VoteMapPanel:SetSize( 500, 400 )
	self.VoteMapPanel:SetTitle( "Vote for the next map" )
	self.VoteMapPanel:SetVisible( true )
	self.VoteMapPanel:SetDraggable( true )
	self.VoteMapPanel:ShowCloseButton( true )
	self.VoteMapPanel:MakePopup()
	self.VoteMapPanel:Center()

		VoteListView = vgui.Create("DListView", self.VoteMapPanel)
		VoteListView:SetPos(25, 50)
		VoteListView:SetSize(450, 325)
		VoteListView:SetMultiSelect(false)
		VoteListView:AddColumn("Map name") -- Add column
		VoteListView:AddColumn("Amount of votes")
		local col = VoteListView:AddColumn("Map Index")
		col:SetWidth( 0 )
		
		function VoteListView.OnClickLine(parent, line, isselected)
			if (HasVoted == false) then
				RunConsoleCommand( "db_map_place_vote", "3141", line:GetValue(3) ) 
				HasVoted = true
				MY_LAST_VOTE = line:GetValue(3)
			else
				if (MY_LAST_VOTE != line:GetValue(3)) then
					RunConsoleCommand( "db_map_remove_vote", "3141", MY_LAST_VOTE )
					RunConsoleCommand( "db_map_place_vote", "3141", line:GetValue(3) )
					MY_LAST_VOTE = line:GetValue(3)
				end
			end
		end
		--Add all the maps to the list
		for k,v in pairs( Maplist ) do
			VoteListView:AddLine( v, "0", k ) -- Add lines
		end
	--Request an update of information
	RunConsoleCommand( "db_map_update" )
end

function GM:HideVoteMap()
	if ( IsValid( self.Vote ) ) then
		self.VoteMapPanel:Remove( )
		self.VoteMapPanel = nil
		VoteListView:Remove( )
		VoteListView = nil
	end
end

//This updates the vote tally in the gui
function PlayerVoted( mess )
	if ( IsValid(VoteListView) ) then
		local message = mess:ReadString( )
		message = string.Explode( ",", message )
		for k, v in pairs( message ) do
			VoteListView:GetLine( k ):SetValue(2, v )
		end
	end
end
usermessage.Hook( "player_voted", PlayerVoted )